import {request} from "../../request/index.js";

Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(wx.getStorageSync("cookieKey")==null||wx.getStorageSync("cookieKey")==""){
      wx.redirectTo({
        url: '../login/index',
      });
      return;
    }
    this.LoadUser();
  },
  //验证用户信息
  async LoadUser(){
   //创建header
   let header;
   header = {
     'content-type': 'application/x-www-form-urlencoded',
     'cookie':wx.getStorageSync("cookieKey")//读取cookie
   };
   const res = await request({ url: "/user/customer/survival", method: "POST",header: header });
   if(res.data.code===200){
     if (res && res.header && res.header['Set-Cookie']) {
       wx.setStorageSync('cookieKey', res.header['Set-Cookie']);   //保存Cookie到Storage
     }
   }else{
     wx.navigateTo({
       url: '../login/index',
     })
   }
  },
  //确认修改密码
  formSubmit(e) {
    var that=this;
    wx.showModal({
      title: '修改密码',
      content: '确认要修改密码？',
      success: function (res) {
        if (res.confirm) {  
          that.formSubmit2(e);
        } else {   
          return;
        }
      }
    })
  },
  //确认后修改个人信息
  async formSubmit2(e){
    const user = e.detail.value;
    if(user.oldpassword==""||user.oldpassword==null||
      user.newpassword==""||user.newpassword==null||
      user.newpassword2==""||user.newpassword2==null){
        wx.showToast({
           title: "内容不能为空",
           icon: 'error',
           mask: true
         });
      return;
    }
    if(user.newpassword!=user.newpassword2){
      wx.showToast({
        title: "两次输入的的密码不相同",
        icon: 'none',
        mask: true
      });
      return;
    }
    //创建header
    let header;
    header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie':wx.getStorageSync("cookieKey")//读取cookie
    };
    const res = await request({ url: "/user/customer/updatePwd", method: "POST", data: user,header: header });
    if (res && res.header && res.header['Set-Cookie']) {
      wx.setStorageSync('cookieKey', res.header['Set-Cookie']);   //保存Cookie到Storage
    }
    const {code,msg} = res.data;
    wx.showToast({
      title: msg,
      icon: 'none',
      mask: true
    });
    if(code===200){
      setTimeout(() => {
        wx.removeStorage({
          key: 'cookieKey',
        });
        wx.reLaunch({
          url: '../login/index',
        });
      }, 1000);
    }
  },
})